import express from "express";
import bodyParser from "body-parser";
import mysql from "mysql";
import Crypto from "./utils/crypto.js";
import { v4 as uuidv4 } from "uuid";
import jwt from "jsonwebtoken";
import authenticateJWT from "./utils/authenticateJWT.js";
import birds from "./services/bird.js"
const port = 3000;
const app = express();
const secret = "motherfucker";
app.use(bodyParser.urlencoded({ extended: false }));

// 连接到数据库
const connection = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "123456",
  database: "books",
});
connection.connect((err) => {
  if (err) throw err;
  console.log("连接数据库成功");
});
app.use('/birds', birds)
app.get("/", (req, res) => {
  res.send("请求地址错误");
});
app.post("/register", (req, res) => {
  // 用户名和密码
  const username = req.body.username;
  const password = req.body.password;
  const confirm_password = req.body.confirm_password;

  // 用户名密码都不能为空
  if (!username && !password && !confirm_password) {
    res.send("用户名或密码不能为空！");
  } else {
    // 密码和确认密码相同
    if (password === confirm_password) {
      // 创建一个新用户
      const p = Crypto.encrypt(password);
      const uuid = uuidv4().toString();
      const user = { username, password: p, uuid };

      // 将新用户插入到数据库中
      connection.query("INSERT INTO user SET ?", user, (err, result) => {
        if (err) throw err;
        res.send("注册成功！");
      });
    } else {
      res.send("两次输入密码不相同");
    }
  }
});
app.post("/login", (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  if (!username && !password) {
    res.send("用户名或密码不能为空！");
  } else {
    const p = Crypto.encrypt(password);
    connection.query(
      "SELECT * FROM user WHERE username = ? AND password = ?",
      [username, p],
      (err, result) => {
        if (err) throw err;
        if (result.length > 0) {
          var token = jwt.sign(
            { username: result[0].username, uuid: result[0].uuid },
            secret,
            { expiresIn: "1h" }
          );
        }
        res.status(200).json({
          token,
          msg: "登录成功！",
          user: {
            username: result[0].username,
            userId: result[0].userId,
          },
        });
      }
    );
  }
});
app.get('/protected', authenticateJWT, (req, res) => {
  res.send({ message: '这是一个受保护的资源！', user: req.user });
});
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});
